﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MyWeb.ServiceBus.Common;
using MyWeb.ServiceBus.Model;
using MyWeb.ServiceBus.Model.Dto;
using MyWeb.ServiceBus.Model.Models;
using MyWeb.ServiceBus.Services;

namespace MyWeb.ServiceBus.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class OrganizationController : ControllerBase
    {
        private IOrganizationService _service;
        public OrganizationController(IOrganizationService service)
        {
            _service = service;
        }

        [HttpGet]
        public async Task<IActionResult> Get()
        {
            var org = await _service.QueryAsync(o=>1==1);
            return Ok(org);
        }
        [HttpGet]
        public async Task<ApiResult> GetPage(int page,int pageSize,string key = "")
        {
            var request = new OrganizationDto()
            {
                Pagination = new PageModel()
                {
                    Page = page,
                    PageSize = pageSize,
                },
                Key = key
            };
            var org = await _service.QueryPageAsync(request);

            var pageData = new PageModel(page, request.Pagination.DataCount,pageSize,org);

            return ApiResult.SUCCESS(res:pageData);
        }

        [HttpPost]
        public async Task<ApiResult> Add(Organization org)
        {
            var organization = await _service.QueryAsync(o => o.Code == org.Code);

            if(organization.Count >= 1)
            {
                return ApiResult.FAILED(msg:"机构编码重复！");
            }
            org.Id = Snowflake.NextId();
            return ApiResult.SUCCESS(res: await _service.AddAsync(org));
        }
        [HttpPut]
        public async Task<ApiResult> Edit(Organization org)
        {
            var organization = await _service.QuerySingleAsync(o => o.Id == org.Id);
            if(organization is not null)
            {
                if(await _service.EditAsync(org) >= 1)
                {
                    return ApiResult.SUCCESS();
                }
                return ApiResult.FAILED();
            }
            else
            {
                return ApiResult.FAILED("没有可修改的对象！");
            }
        }
        [HttpDelete]
        public async Task<ApiResult> Remove(long id)
        {
            var org = await _service.QuerySingleAsync(o => o.Id == id);
            if (org is not null)
            {
                if (await _service.Remove(org) >= 1)
                {
                    return ApiResult.SUCCESS();
                }
                return ApiResult.FAILED();
            }
            else
            {
                return ApiResult.FAILED("没有可删除的对象！");
            }
        }
    }
}
